<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\self\SelfRedis;
use think\Model;

/**
 * @mixin \think\Model
 */
class Config extends Model
{
    public const TYPE_WECHAT = 'wechat'; // 微信的配置

    //获取配置
    public function toData($type)
    {
        if ($type == self::TYPE_WECHAT) {
            $config = config('wechat');
        } else {
            $config = $this->where(['type' => $type])->value('content');
        }
        if (empty($config))
            return [];
        if (is_string($config))
            $config = json_decode($config, true);
        return $config;
    }

    //注册协议图文保存
    public function toReg($data)
    {
        try {
            if (empty($data['editorValue']))
                return_ajax(400, '注册协议不能为空');

            $content = htmlspecialchars($data['editorValue']);
            if ($this->where(['type' => 'reg'])->find()) {
                $this->allowField(true)->isUpdate(true)->save(['content' => json_encode(['content' => $content])], ['type' => 'reg']);
                $msg = '配置修改成功';
            } else {
                $this->allowField(true)->save(['content' => json_encode(['content' => $content]), 'type' => 'reg']);
                $msg = '配置保存成功';
            }
            return_ajax(200, $msg);
        } catch (\Exception $e) {
            return_ajax(400, $e->getMessage());
        }
    }

    //重装access_token并保存 小程序
    public function getAccessToken()
    {
        try {
            $sr = new SelfRedis();
            $access_token = $sr->redis->get('access_token');
            if (!empty($access_token))
                return $access_token;
            $config = $this->where(['type' => 'wechat'])->value('content');
            $wachat = json_decode($config, true);
            if (!empty($wachat['appid'])) {
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wachat['appid']}&secret={$wachat['appsecret']}";
                $ret = curlGet($url);
                $retData = json_decode($ret, true);
                if (!empty($retData['access_token'])) {
                    $sr->redis->set('access_token', $retData['access_token'], 7200);
                    return $retData['access_token'];
                } else {
                    $errMpa = [-1 => '系统繁忙，此时请开发者稍候再试', 40001 => 'AppSecret 错误或者 AppSecret 不属于这个小程序，请开发者确认 AppSecret 的正确性', 40002 => '请确保 grant_type 字段值为 client_credential', 40013 => '不合法的 AppID，请开发者检查 AppID 的正确性，避免异常字符，注意大小写'];
                    if (!empty($retData['errcode'])) exception($errMpa[$retData['errcode']]);
                    else exception('系统繁忙');
                }
            }
            exception('小程序配置有误');
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * 拿取字段并缓存
     */
    public function getSrTypes($key)
    {
        if (!$key) return false;
        $sr = new SelfRedis();
        $sr->redis->select(11);
        $data = $sr->redis->get('config_' . $key);
        if (!$data || !is_array($data)) {
            if (!$model = $this::where('type', $key)->field('content')->find()) return false;
            $data = json_decode($model->content);
            $sr->redis->set('config_' . $key, $data);
        }
        return $data;
    }
}